var money = (function ($) {
    var paramsHightChatrs = {};
    return {
        showFormProfit : function (profitId) {
            $.get('/ajax/geteditprofit', {"id": profitId}, function (html) {
                var options = {};
                if (!profitId) {
                    options = {"onConfirm" : money.saveProfit, "title": "Добавить доход"};
                } else {
                    options= {
                        "buttons":{
                            confirm: "Да",
                            chancel: "Удалить"
                        },
                        "onConfirm" : money.saveProfit,
                        "onChancel" : money.deleteProfit,
                        "title": "Редактирование доходов"
                    }
                }

                modal.confirm(html, options);
            });
        },
        saveProfit : function () {
            var formObj = $('#edit_profit'),
                summ    = formObj.find('#summ_profit'),
                date    = formObj.find('#date_profit'),
                id      = formObj.find('#profit_id');

            $.get('/ajax/editprofit/', {'id': id.val(), 'date': date.val(), 'summ': summ.val()}, function (data) {
                switch (data.status) {
                    case 'success':
                        mn.notify('success', {text: "Запись обновлена"});
                        money.showHighcharts(paramsHightChatrs);
                        break;
                    case 'error':
                        break;
                }
            });
        },
        deleteMoney: function (id, type) {
            $.get('/ajax/delete/', {'id': id, 'type': type}, function (data) {
                switch (data.status) {
                    case 'ok':
                        mn.notify('success', {text: 'Запись удалена!'});
                        break;
                    case 'error':
                        break;
                }
            });
        },
        deleteProfit: function () {
            var formObj = $('#edit_profit'),
                id = formObj.find('#profit_id');

            money.deleteMoney(id.val(), 'profit');
            money.showHighcharts(paramsHightChatrs);
        },
        showDebts: function (type, element) {
            var el = $(element);

            $.get('/ajax/getdebts',{"type":type}, function (data) {
                if (data.status == 'no_debts') {
                    modal.open(data.html, {title: "Добавить долг"});
                    return true;
                }
                mn.popover(el, data, {"placement":'left'});
            });
        },
        showFormDebt: function (id) {
            id = id || '';
            var title = "Добавить долг";
            $.get('/ajax/geteditdebt',{"id" : id}, function (data) {

                if (data.id) {
                    title = "Редактировать долг";
                }

                modal.open(data.html, {title: title});
            });
        },
        saveDebt: function () {
            var form = $('#edit_debt'),
                types = form.find('input[name="type_debt"]'),
                checkedTypeValue,
                countTypes = types.length,
                name       = form.find('#name_debt'),
                id         = form.find('#debt_id'),
                summ       = form.find('#summ_debt'),
                dateDebt   = form.find('#date_debt'),
                dateReturn = form.find('#date_return');

        for (var i = 0; i < countTypes; i++) {
            if (types[i].checked) {
                checkedTypeValue = $(types[i]).val();
            }
        }

        $.get('/ajax/savedebt/', {
            'debt_id'     : id.val(),
            'date_debt'   : dateDebt.val(),
            'date_return' : dateReturn.val(),
            'name'        : name.val(),
            'summ'        : summ.val(),
            'type_debt'   : checkedTypeValue
        }, function (data) {
            if (data.status != 'error') {
                modal.close();

                if (data.status == 'ok') {
                    mn.notify('success', {text: 'Долг изменен!'});
                } else {
                    mn.notify('success', {text: 'Долг добавлен!'});
                }
            }
        });

        },
        showHighcharts : function (options) {
            paramsHightChatrs = {};
            $.extend(paramsHightChatrs, options);

            $.get('/ajax/getprofits', paramsHightChatrs, function (data) {
                var series = [],
                    profits = data.profits;

                for (year in profits) {
                    var item = [],
                        dataForItem = [];

                    if (!paramsHightChatrs.sort || paramsHightChatrs.sort == 1) { //Application_Model_ProfitMapper::BY_DAYS
                        $.each(profits[year], function () {
                            //чтоб отображалось всё на одном графике поставим всем по умолчанию год 2000
                            dataForItem.push([Date.UTC(2000,  parseInt(this.month) - 1, parseInt(this.day)), parseInt(this.summ), this.id]);
                        });
                    }

                    if (paramsHightChatrs.sort == 2) { //Application_Model_ProfitMapper::BY_MONTH
                        var months = [],
                            profitsByDays = {};

                        $.each(profits[year], function () {
                            var summ = parseInt(this.summ),
                                month = parseInt(this.month);

                            if (typeof(months[month]) != "undefined") {
                                months[month] = months[month] + summ;
                            } else {
                                months[month] = summ;
                                profitsByDays[month] = [];
                            }

                            profitsByDays[month].push(this);
                        });

                        for (i in months) {
                            dataForItem.push([Date.UTC(2000, i - 1), parseInt(months[i]), profitsByDays[i]]);
                        }
                    }

                    item = {
                        name: year,
                        data: dataForItem,
                        marker: {
                            radius: 5
                        }
                    };

                    series.push(item);
                }

                var chart;

                chart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'container-highcharts',
                        type: 'spline'
                    },
                    title: {
                        text: 'График доходов'
                    },
                    subtitle: {
                        text: 'Доход за период времени'
                    },
                    xAxis: {
                        type: 'datetime',
                        dateTimeLabelFormats: { // don't display the dummy year
                            month: '%b',
                            year: '%b'
                        }
                    },
                    yAxis: {
                        title: {
                            text: 'Полученная сумма (р)'
                        },
                        min: 0
                    },
                    tooltip: {
                        formatter: function() {
                            return '<b>'+ this.series.name +'</b><br/>'+
                                Highcharts.dateFormat('%e. %b', this.x) +': '+ this.y +' р';
                        }
                    },
                    plotOptions: {
                        series: {
                            cursor: 'pointer',
                            point: {
                                events: {
                                    click: function() {
                                        var profitId = parseInt(this.config[2]);

                                        if (profitId) {
                                            money.showFormProfit(profitId);
                                        } else {
                                            money.showTooltipMonthProfit($('#container-highcharts'), this.config[2]);
                                        }
                                    }
                                }
                            },
                            marker: {
                                lineWidth: 1
                            }
                        }
                    },
                    series: series
                });
            });
        },
        showTooltipMonthProfit: function (el, daysProfits) {
            var data = "<table class=\"table table-striped table-debt\">" +
                "<thead><tr><th>Дата</th><th>Сколько</th></tr></thead><tbody>";
            for (i in daysProfits) {
                data += "<tr onclick=\"money.showFormProfit(" + daysProfits[i]["id"] + ")\"> " +
                    "<td>" + daysProfits[i]["day"] + "." + daysProfits[i]["month"] + "." + daysProfits[i]["year"]  + "</td>"+
                    "<td>" + daysProfits[i]["summ"] + "р. </td>" +
                    "</tr>";
            }

            data += "</tbody></table>";

            mn.popover(el, data, {"placement":'right'});
        },
        getValueFilters: function () {
            var selects = $('select'),
                values = [];

            $.each(selects, function () {
                var el = $(this),
                    name = el.attr('name');

                values[name] = el.val();
            });

            return values;
        }
    }
})(jQuery);